<!DOCTYPE html>

<head>

    <title>递归分形树（三）</title>

</head>

<body>

    <canvas id="myCanvas" width="600" height="400" style="border:3px double #996633;"></canvas>

    <script type="text/javascript">

        var canvas = document.getElementById('myCanvas');

        var ctx = canvas.getContext('2d');

        var maxdepth = 10;

        var curdepth = 0;

        function growtree() {

            ctx.translate(300, 380);

            branch(-Math.PI / 2);

        }

        function branch(angle) {

            curdepth++;

            ctx.save();

            ctx.strokeStyle = "green";

            ctx.lineWidth = 6;

            ctx.rotate(angle);

            ctx.beginPath();

            ctx.moveTo(0, 0);

            ctx.lineTo(100, 0);

            ctx.stroke();

            ctx.translate(100, 0);

            ctx.scale(0.75, 0.75);

            if (curdepth < maxdepth) {

                branch(randomRange(0, Math.PI / 4));

                branch(randomRange(-Math.PI / 4, 0));

            }

            if (curdepth == maxdepth) {

                ctx.fillStyle = '#ff0000';

                ctx.beginPath();

                ctx.arc(0, 0, 20, 0, Math.PI * 2, true);

                ctx.fill();

            }

            ctx.restore();

            curdepth--;

        }

        function randomRange(min, max) {

            return Math.random() * (max - min) + min;

        }

        growtree();

    </script>

</body>

</html>